<template>
  <div>
    <div>
      <van-nav-bar
        title="购物车"
        left-text=""
        left-arrow
        @click-left="onClickLeft"
      />
    </div>
    <div>
      <!-- 内容为空时显示空白页 -->
      <div class="kong" v-if="listdata.length <= 0">
        <van-empty description="暂无数据" />
      </div>
      <!-- 内容不为空时显示商品列表 -->
      <div v-else>
        <van-swipe-cell v-for="(item, index) in listdata" :key="index">
          <van-card
            :price="item.discount"
            :desc="item.title"
            :title="item.title"
          >
            <template #thumb>
              <div class="imgbox">
                <van-checkbox v-model="item.checked" />&emsp;
                <img v-lazy="item.img" alt="" class="img" />
              </div>
            </template>
            <template #footer>
              <van-button
                size="mini"
                @click="addnum(item)"
                style="width: 0.3rem"
                >+</van-button
              >
              &nbsp;<span>{{ item.num }}</span
              >&nbsp;
              <van-button
                size="mini"
                @click="subtractnum(item)"
                style="width: 0.3rem"
                >-</van-button
              >
            </template>
          </van-card>
          <template #right>
            <van-button
              @click="showConfirm(index)"
              square
              text="删除"
              type="danger"
              class="delete-button"
            />
          </template>
        </van-swipe-cell>
        <!-- 删除确认对话框 -->
        <van-dialog
          v-model:show="show"
          title="确认删除这个商品吗？"
          show-cancel-button
          @confirm="deletecar"
        >
        </van-dialog>
      </div>
    </div>

    <!-- 底部 -->
    <div>
      <van-submit-bar
        :price="priceAll"
        button-text="提交订单"
        @submit="onSubmit"
      >
        <van-checkbox v-model="checkedAll">全选</van-checkbox>
      </van-submit-bar>
    </div>
    <van-overlay :show="pop" @click="pop = false" z-index="999">
      <div class="wrapper">
        <div class="box">
          <h3>支付</h3>
          <p>您是否确定购买</p>
          <button class="giveup" @click="onGiveUp">残忍放弃</button
          ><button class="purchase" @click="onPurchase">确认购买</button>
        </div>
      </div>
    </van-overlay>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, watch } from "vue";
import { useCounterStore } from "../../pinia/index";
import { showToast } from "vant";
import instance from "../../axios/index";
import { useRouter } from "vue-router";
const pop = ref(false);
interface Item {
  discount: number;
  title: string;
  img: string;
  checked: boolean;
  num: number;
}
const router = useRouter();
const onClickLeft = () => history.back();

const listdata = ref<Item[]>([]);
const store = useCounterStore();
listdata.value = store.caradd;

// 计算徽标数量（购物车中商品总数量）
const badgeNum = computed(() => {
  return listdata.value.reduce((acc, item) => acc + item.num, 0);
});

// 利用watch监听listdata变化，实时更新store.carnum
watch(
  listdata,
  () => {
    store.carnum = badgeNum.value;
  },
  { deep: true }
); // 设置deep为true，以便深度监听数组内部元素变化（比如对象属性变化等情况）

store.carnum = badgeNum.value;
// 计算总价
const priceAll = computed(() => {
  let priceAll = 0;
  const select = listdata.value.filter((item) => item.checked);
  select.forEach((item) => {
    priceAll += item.num * item.discount * 100;
  });
  return priceAll;
});

// 全选的计算属性及设置逻辑
const checkedAll = computed({
  get() {
    return listdata.value.every((item) => item.checked);
  },
  set(val) {
    listdata.value.forEach((item) => (item.checked = val));
  },
});

// 减少数量
const subtractnum = (item: Item) => {
  if (item.num > 1) {
    item.num--;
  } else {
    showToast("数量不能再减少啦");
  }
};

// 增加数量
const addnum = (item: Item) => {
  item.num++;
};

// 是否显示确认框
const show = ref(false);
// 当前索引
const currentIndex = ref(-1);

// 显示确认框
const showConfirm = (index: number) => {
  currentIndex.value = index;
  show.value = true;
};

// 删除购物车
const deletecar = () => {
  store.caradd.splice(currentIndex.value, 1);
  show.value = false;
};

// 提交订单逻辑
const onSubmit = () => {
  pop.value = true;
};

// 点击放弃支付
const onGiveUp = () => {
  pop.value = false;
  // 获取我点击放弃的时间
  const time = new Date();
  // 将我点击放弃的时间存储到本地
  // @ts-ignore
  localStorage.setItem("usedtime", time.getTime());
  // 将我选中的商品添加到订单中
  listdata.value.forEach((value, index) => {
    if (value.checked == true) {
      // @ts-ignore
      store.order.push(value);
    }
  });
  // 自动跳转至订单页面
  router.push("/homeorder");
};
// 点击确认支付
const onPurchase = () => {
  // 遮罩层消失
  pop.value = false;
  // 生命沙箱的id 和 选中商品总价传入沙箱支付
  let data = {
    id: Math.random().toString(36).substr(2),
    price: priceAll.value / 100,
  };
  // 调用沙箱接口
  instance.get("/api/pay", { params: data }).then((res) => {
    window.open(res.data.data);
  });
};
</script>

<style lang="scss" scoped>
.goods-card {
  margin: 0;
}

.delete-button {
  height: 100%;
}

.imgbox {
  display: flex;
  flex: 1;
}

.img {
  width: 0.8rem;
  height: 0.8rem;
}

:deep(.van-card__thumb) {
  width: 1.2rem;
}

.van-card {
  margin-bottom: 0.1rem;
}
.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}
.box {
  width: 3rem;
  height: 1.7rem;
  background-color: #fff;
  text-align: center;
  border-radius: 0.2rem;
  overflow: hidden;
}
.box h3 {
  // line-height: 0.5rem;
  padding-top: 0.2rem;
}
.box p {
  line-height: 0.75rem;
  color: #696768;
}
.box button {
  width: 50%;
  background-color: #fff;
  height: 0.5rem;
}
.giveup {
  border-bottom: none;
  border-left: none;
  border-right: none;
  border-top: 1px solid #ccc;
  color: #3897fa;
}
.purchase {
  border-bottom: none;
  border-left: 1px solid #ccc;
  border-right: none;
  border-top: 1px solid #ccc;
  color: rgb(255, 61, 61);
}
</style>